package org.example.classtopia.Service.Impl;

import org.example.classtopia.Mapper.PostMapper;
import org.example.classtopia.Mapper.UserMapper;
import org.example.classtopia.Model.dto.PostCreateDTO;
import org.example.classtopia.Model.dto.PostUpdateDTO;
import org.example.classtopia.Model.Entity.Post;
import org.example.classtopia.Model.Entity.User;
import org.example.classtopia.Model.vo.PageResultVO;
import org.example.classtopia.Model.vo.PostPreviewVO;
import org.example.classtopia.Model.vo.PostVO;
import org.example.classtopia.Model.vo.MyPostSimpleVO;
import org.example.classtopia.Service.PostService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostMapper postMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public Post createPost(PostCreateDTO postCreateDTO) {
        // 根据authorId获取用户信息
        User user = userMapper.FindCommonData(postCreateDTO.getAuthorId());
        if (user == null) {
            return null; // 用户不存在
        }
        
        Post post = new Post();
        BeanUtils.copyProperties(postCreateDTO, post);
        post.setAuthorNickname(user.getNickname());
        post.setAuthorAvatar(user.getAvatar());
        post.setStatus(0);
        post.setCommentCount(0);
        post.setLikeCount(0);
        LocalDateTime now = LocalDateTime.now();
        post.setCreateTime(now);
        post.setUpdateTime(now);
        int rows = postMapper.insertPost(post);
        return rows > 0 ? post : null;
    }

    @Override
    public PostVO getPostById(Long id) {
        Post post = postMapper.selectPostById(id);
        if (post == null) {
            return null;
        }
        PostVO vo = new PostVO();
        BeanUtils.copyProperties(post, vo);
        // 如果有更多展示字段(比如作者昵称等)，这里可以补充赋值
        return vo;
    }

    @Override
    public PageResultVO<PostVO> getPostsByAuthorId(Long authorId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        // 查询分页数据
        List<Post> postList = postMapper.selectPostsByAuthorId(authorId, offset, pageSize);

        // 查询总记录数
        Long total = postMapper.countPostsByAuthorId(authorId);

        // 转成VO
        List<PostVO> voList = postList.stream().map(post -> {
            PostVO vo = new PostVO();
            BeanUtils.copyProperties(post, vo);
            return vo;
        }).collect(Collectors.toList());

        // 计算总页数
        int totalPages = (int) ((total + pageSize - 1) / pageSize);

        // 封装分页结果
        PageResultVO<PostVO> pageResult = new PageResultVO<>();
        pageResult.setRecords(voList);
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setTotal(total);
        pageResult.setTotalPages(totalPages);

        return pageResult;
    }


    @Override
    public boolean updatePost(PostUpdateDTO postUpdateDTO) {
        // 先查出原有数据
        Post old = postMapper.selectPostById(postUpdateDTO.getId());
        if (old == null) return false;
        Post post = new Post();
        post.setId(old.getId());
        // 只更新有传入的字段，否则用原值
        post.setTitle(postUpdateDTO.getTitle() != null ? postUpdateDTO.getTitle() : old.getTitle());
        post.setContent(postUpdateDTO.getContent() != null ? postUpdateDTO.getContent() : old.getContent());
        post.setStatus(postUpdateDTO.getStatus() != null ? postUpdateDTO.getStatus() : old.getStatus());
        post.setCategoryId(postUpdateDTO.getCategoryId() != null ? postUpdateDTO.getCategoryId() : old.getCategoryId());
        post.setUpdateTime(java.time.LocalDateTime.now());
        // 其他字段如有需要可补充
        post.setCommentCount(old.getCommentCount());
        post.setLikeCount(old.getLikeCount());
        int rows = postMapper.updatePost(post);
        return rows > 0;
    }

    @Override
    public boolean deletePostById(Long id) {
        int rows = postMapper.deletePostById(id);
        return rows > 0;
    }

    @Override
    public List<PostVO> getAllPosts(int offset, int limit) {
        List<Post> postList = postMapper.selectAllPosts(offset, limit);
        return postList.stream()
                .map(post -> {
                    PostVO vo = new PostVO();
                    BeanUtils.copyProperties(post, vo);
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public PageResultVO<PostVO> searchPosts(String keyword, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;

        // 分页数据
        Map<String, Object> params = new HashMap<>();
        params.put("keyword", keyword);
        params.put("offset", offset);
        params.put("limit", pageSize);
        List<Post> posts = postMapper.searchPosts(params);

        // 总数
        Long total = postMapper.countSearchPosts(keyword);

        // 转VO
        List<PostVO> voList = posts.stream().map(this::toVO).collect(Collectors.toList());

        // 计算总页数
        int totalPages = (int) ((total + pageSize - 1) / pageSize);

        // 封装分页VO
        PageResultVO<PostVO> pageResult = new PageResultVO<>();
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setRecords(voList);
        pageResult.setTotal(total);
        pageResult.setTotalPages(totalPages);

        return pageResult;
    }

    @Override
    public List<PostPreviewVO> getPostPreviews(int offset, int size) {
        return postMapper.getPostPreviews(offset, size);
    }

    @Override
    public List<PostPreviewVO> getAllPostPreviews(int offset, int size) {
        return postMapper.getAllPostPreviews(offset, size);
    }

    @Override
    public List<PostPreviewVO> getAllPostPreviewsByCategory(Long categoryId, int offset, int size) {
        return postMapper.getAllPostPreviewsByCategory(categoryId, offset, size);
    }

    @Override
    public long countAllPostsByCategory(Long categoryId) {
        return postMapper.countAllPostsByCategory(categoryId);
    }

    @Override
    public List<PostPreviewVO> getPostPreviewsByCategory(Long categoryId, int offset, int size) {
        return postMapper.getPostPreviewsByCategory(categoryId, offset, size);
    }

    @Override
    public long countNormalPostsByCategory(Long categoryId) {
        return postMapper.countNormalPostsByCategory(categoryId);
    }

    private PostVO toVO(Post post) {
        PostVO vo = new PostVO();
        BeanUtils.copyProperties(post, vo);
// 如有更多字段赋值可在此补充
        return vo;
    }

    @Override
    public PageResultVO<Post> getPostsByCategory(Long categoryId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Post> posts = postMapper.getPostsByCategory(categoryId);
        PageInfo<Post> pageInfo = new PageInfo<>(posts);
        return toPageResult(pageInfo, pageNum, pageSize);
    }

    private <T> PageResultVO<T> toPageResult(PageInfo<T> pageInfo, int pageNum, int pageSize){
        PageResultVO<T> result = new PageResultVO<>();
        result.setRecords(pageInfo.getList());
        result.setPageNum(pageNum);
        result.setPageSize(pageSize);
        result.setTotal(pageInfo.getTotal());
        result.setTotalPages(pageInfo.getPages());
        return result;
    }

    @Override
    public long countAllPosts() {
        return postMapper.countAllPosts();
    }

    @Override
    public long countNormalPosts() {
        return postMapper.countNormalPosts();
    }

    @Override
    public List<MyPostSimpleVO> getMyAllPosts(Long authorId) {
        return postMapper.getMyAllPosts(authorId);
    }
    @Override
    public List<MyPostSimpleVO> getMyAllPostsPaged(Long authorId, int offset, int size) {
        return postMapper.getMyAllPostsPaged(authorId, offset, size);
    }
    @Override
    public long countMyAllPosts(Long authorId) {
        return postMapper.countMyAllPosts(authorId);
    }
}

